import { showToast, getLocation, chooseImage, upload } from "/utils/common";
import { bus } from "/utils/core";
import request from "/utils/request"
import omsRequest from "/utils/omsRequest"
import { getClockStatus, getHistoryVisitInfo, clockStart, clockEnd, addImage, addAccompany, addWordRecord } from "/api/clock/index"
import { moment } from "/utils/core";
import validator from "/utils/validators";
const Promise = require('/plugins/es6-promise')
const app = getApp()

Page({
  data: {
    form: {
      accompanyList: [], // 陪访人员列表
      address: "", // 打卡地点
      devices: "", // 打卡设备
      lat: "", // 打卡纬度
      lng: "", // 打卡经度
      id: null, // 打卡数据id
      merchantId: null, // 商户id
      shopId: null, // 门店id
    },
    merchant: null, // 拜访的商户
    merchantStatus: null,
    visibleDrawer: false, // 显示商户选择
    time: null, // 当前时间
    timer: null, // 当前时间计时器
    totalTime: null, // 拜访总总间,
    totalTimer: null, //拜访总时间计时器
    systemInfo: null,
    userList: [], // 陪访人员列表
    userMap: {}, // 用户map映射
  },
  onLoad() {
    this.initLaction()
    app.getUnderUserList().then(list => {
      let obj = {}
      list.forEach(user => {
        obj[user.dingUserId] = user.dingUserName
      });
      this.setData({
        userList: list,
        userMap: obj
      })
    })
    this.setData({
      time: moment().format("HH:mm:ss"),
      systemInfo: app.globalData.systemInfo
    })
    const timer = setInterval(() => {
      this.setData({
        time: moment().format("HH:mm:ss")
      })
    }, 1000)
    this.setData({
      timer: timer
    })
    dd.getStorage({
      key: 'clockHistoryInfo',
      success: (res) => {
        if (res.data) {
          this.onClockInit(res.data, true)
        }
      },
      fail: function (res) {
        dd.alert({ content: res.errorMessage });
      }
    });
  },
  onUnload() {
    clearInterval(this.data.timer)
    clearInterval(this.data.totalTimer)
  },
  // 显示拜访商户
  onMerchantSelect() {
    if (this.data.form.id === null) {
      this.setData({
        visibleDrawer: true
      })
    }
  },
  // 关闭拜访商户
  onDrawerClose() {
    this.setData({
      visibleDrawer: false
    })
  },
  // 选择商户初始化数据
  onClockInit(merchant, bool) {
    clearInterval(this.data.totalTimer)
    dd.setStorage({
      key: 'clockHistoryInfo',
      data: merchant
    });
    this.onDrawerClose()
    this.setData({
      form: {
        accompanyList: [],
        address: "",
        devices: "",
        lat: "",
        lng: "",
        id: null,
        merchantId: merchant.id,
        shopId: merchant.shop.id,
      },
      merchant: merchant,
      totalTime: null,
      time: null
    })
    !bool && this.initLaction()
    this.getLastVisitInfo({
      crmMerchantId: merchant.id,
      shopId: merchant.shop.id
    }).then(() => {
      this.getClockInfo({
        crmMerchantId: merchant.id,
        shopId: merchant.shop.id
      })
    })
  },
  // 获取上次拜访时间和次数
  getLastVisitInfo(params) {
    return new Promise((resolve, reject) => {
      dd.showLoading({
        content: "加载中..."
      })
      request({
        url: getHistoryVisitInfo,
        data: params
      }).then((res) => {
        this.setData({
          "merchant.visitCount": res.vo.visitCount,
          "merchant.visitDate": res.vo.visitDate ? moment(res.vo.visitDate).format("YYYY-MM-DD HH:mm:ss") : '暂无'
        })
        resolve()
      }).finally(() => {
        dd.hideLoading()
      })
    })
  },
  // 获取当前商户的打卡信息
  getClockInfo(params) {
    dd.showLoading({
      content: "加载中..."
    })
    request({
      url: getClockStatus,
      data: params
    }).then(res => {
      if (res.vo === null) {
        // 未打卡
        this.setData({
          merchantStatus: null
        })
      } else {
        // 已打卡
        this.onClockHistoryInfoInit(params, res)
      }
    }).finally(() => {
      dd.hideLoading()
    })
  },
  onClockHistoryInfoInit(params, res) {
    bus.publish('queryWordRecordList', params) // 获取商户历史打卡文字语音记录
    let date = moment(moment().diff(moment(res.vo.startDate), 'm'))
    this.setData({
      "form.id": res.vo.id,
      "totalTime": `${Math.floor(date / 60)}小时${date % 60}分钟`,
      "merchantStatus": res.vo,
      "form.accompanyList": res.vo.accompanyList
    })
    const timer = setInterval(() => {
      date = moment(moment().diff(moment(res.vo.startDate), 'm'))
      this.setData({
        "totalTime": `${Math.floor(date / 60)}小时${date % 60}分钟`
      })
    }, 10000)
    this.setData({
      totalTimer: timer
    })
  },
  // 打卡
  onClock() {
    if (this.data.merchant) {
      this.initLaction().then(() => {
        const { accompanyList, address, devices, lat, lng, id, merchantId, shopId } = this.data.form
        let validate = new validator();
        validate.add("checkEmpty", address, "地址不能为空");
        validate.add("checkEmpty", devices, "打卡设备不能为空");
        validate.add("checkEmpty", lat, "纬度不能为空");
        validate.add("checkEmpty", lng, "经度不能为空");
        validate.add("checkEmpty", merchantId, "商户id不能为空");
        validate.add("checkEmpty", shopId, "门店id不能为空");
        if (validate.check()) {
          if (this.data.form.id === null) {
            // 开始打卡
            this.onClockStart({
              accompanyList,
              crmMerchantId: merchantId,
              shopId,
              startAddress: address,
              startDevices: devices,
              startLat: lat,
              startLng: lng
            })
          } else {
            // 结束打卡
            this.onClockEnd({
              accompanyList,
              endAddress: address,
              endDevices: devices,
              endLat: lat,
              endLng: lng,
              id,
              merchantId,
              shopId
            })
          }
        }
      })
    }
  },
  // 开始打卡
  onClockStart(params) {
    dd.showLoading({
      content: "加载中..."
    })
    request({
      url: clockStart,
      headers: {
        "Content-Type": "application/json"
      },
      method: "post",
      data: params
    }).then(res => {
      this.onClockHistoryInfoInit(params, res)
    }).finally(err => {
      dd.hideLoading()
    })
  },
  // 结束打卡
  onClockEnd(params) {
    dd.showLoading({
      content: "加载中..."
    })
    request({
      url: clockEnd,
      headers: {
        "Content-Type": "application/json"
      },
      method: "post",
      data: params
    }).then(res => {
      dd.alert({
        title: '结束打卡成功！'
      })
      clearInterval(this.data.totalTimer)
      dd.setStorage({
        key: 'clockHistoryInfo',
        data: null
      });
      this.setData({
        form: {
          accompanyList: [],
          address: "",
          devices: "",
          lat: "",
          lng: "",
          id: null,
          merchantId: null,
          shopId: null,
        },
        merchant: null,
        merchantStatus: null
      })
      this.initLaction()
    }).finally(err => {
      dd.hideLoading()
    })
  },
  // 上传门店图
  onUploadImg(e) {
    // 王鑫龙、康蕾、陈小燕
    const whiteList = ['2952654729644121', '15946099046287581', '244432382837731310'];
    chooseImage({ sourceType: whiteList.includes(app.globalData.userInfo.dingUserId) ? ['camera', 'album'] : ['camera'] }).then(({ tempFilePaths }) => {
      if (tempFilePaths.length > 0) {
        dd.showLoading({
          content: "加载中..."
        })
        upload({
          url: tempFilePaths[0],
          type: 'image',
          compressFlag: true
        }).then(({ fileName, fileUrl }) => {
          request({
            url: addImage,
            method: 'post',
            headers: {
              "Content-Type": "application/json"
            },
            data: {
              businessObjId: this.data.form.id,
              category: e.target.dataset.type,
              fileName,
              fileUrl
            }
          }).then(res => {
            if (res.success) {
              switch (e.target.dataset.type) {
                case 'VISIT_SHOP_IMG':
                  this.setData({
                    "merchantStatus.shopImg": {
                      fileName,
                      fileUrl
                    }
                  })
                  break;
                case 'VISIT_SHOP_INTERIOR_IMG':
                  this.setData({
                    "merchantStatus.shopInteriorImg": {
                      fileName,
                      fileUrl
                    }
                  })
                  break;
                case 'VISIT_OTHER_IMG':
                  this.setData({
                    "merchantStatus.otherImg": {
                      fileName,
                      fileUrl
                    }
                  })
                  break;
              }
              dd.hideLoading()
            }
          }).catch(() => {
            dd.hideLoading()
          })
        }).catch(() => {
          dd.hideLoading()
        })
      }
    })
  },
  // 添加陪同人员
  onAccompanyAdd(user) {
    let arr = []
    if (this.data.form.accompanyList) {
      arr = [...this.data.form.accompanyList, user.dingUserId]
    } else {
      arr = [user.dingUserId]
    }
    dd.showLoading({
      content: "加载中..."
    })
    request({
      url: addAccompany,
      method: 'post',
      headers: {
        "Content-Type": "application/json"
      },
      data: {
        id: this.data.form.id,
        accompanyList: arr
      }
    }).then(res => {
      if (!this.data.form.accompanyList) {
        this.data.form.accompanyList = []
      }
      this.data.form.accompanyList.push(user.dingUserId)
      this.setData({
        "form.accompanyList": this.data.form.accompanyList
      })
    }).finally(() => {
      dd.hideLoading()
    })
  },
  initLaction() {
    return new Promise((resolve => {
      getLocation().then(res => {
        this.setData({
          "form.lat": res.latitude,
          "form.lng": res.longitude,
          "form.address": res.address || "无法获取地址名称",
          "form.devices": this.data.systemInfo.model
        })
        resolve(res)
      })
    }))
  }
});
